(function() {
    'use strict';

    angular.module('app.auth')
        .service('AuthenticationService', ['$http', '$rootScope', 'SessionService', 'restBaseUrl', AuthenticationService])
        .service('SessionService', [SessionService])

    function AuthenticationService ($http, $rootScope, SessionService, restBaseUrl) {
        var serviceName = 'AutenticacionService.svc/',
            apiURL = restBaseUrl + serviceName;

        var cacheSession = function(response) {
            if (response) {
                SessionService.set('authenticated', true);
                SessionService.set('userInformation', response);
                $rootScope.userInformation = angular.fromJson(response);
            }
        };

        var uncacheSession = function() {
            SessionService.unset('authenticated');
        };

        var sanitizeCredentials = function(credentials) {
            return {
                Usuario: credentials.user,
                Clave: credentials.pass
            };
        };

        this.login = function(credentials) {
            var req = {
                method: 'POST',
                url: apiURL + 'IniciarSesion',
                data: sanitizeCredentials(credentials),
                headers: {
                    'content-type': 'text/plain'
                }
            };

            var login = $http(req);
            login.success(cacheSession);
            return login;
        };

        this.logout = function() {
            // var req = {
            //     method: 'GET',
            //     url: apiURL + 'Logout'
            // };

            // var logout = $http(req);
            // logout.success(uncacheSession);
            // return logout;
            uncacheSession();
        };

        this.isLoggedIn = function() {
            return SessionService.get('authenticated');
        };

        this.getUserInformation = function() {
            return angular.fromJson(SessionService.get('userInformation'));
        };
    }

    function SessionService () {
        this.get = function(key) {
          return sessionStorage.getItem(key);
        };

        this.set = function(key, val) {
          return sessionStorage.setItem(key, val);
        };

        this.unset = function(key) {
          return sessionStorage.removeItem(key);
        };
    }

})();